package com.yuchting.dinneronline.client;

import java.util.Vector;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.yuchting.dinneronline.client.common.CommonDialog;
import com.yuchting.dinneronline.client.common.Config;
import com.yuchting.dinneronline.client.common.User;
import com.yuchting.dinneronline.client.common.YesNoHandler;
import com.yuchting.dinneronline.client.common.YuchFlexTable;
import com.yuchting.dinneronline.client.common.YuchJSONObject;
import com.yuchting.dinneronline.client.common.YuchSimplePanel;
import com.yuchting.dinneronline.share.ShareField;

public class ConfigAccPanel extends VerticalPanel{
	
	// config panel
	final RichTextArea m_configPrompt	= new RichTextArea ();
	final RichTextToolbar m_configToolbar 	= new RichTextToolbar(m_configPrompt);

	final TextBox	m_startHour		= new TextBox();
	final TextBox	m_startMinutes	= new TextBox();
	final TextBox	m_endHour		= new TextBox();
	final TextBox	m_endMinutes	= new TextBox();
	
	// account panel
	FlexTable		m_accountTable = new YuchFlexTable();
	Vector<User>	m_accountList	= new Vector<User>();

	final MainPanel		m_mainPanel;
	
	Config	m_storeConfig;
	
	static ConfigAccPanel sm_configPanel = null;
	
	public ConfigAccPanel(MainPanel _mainPanel){
		m_mainPanel	= _mainPanel;
		
		sm_configPanel = this;
		
		// config panel
		//
		VerticalPanel t_configPanel = new YuchSimplePanel();
		t_configPanel.setWidth(CommonDialog.getElementWidth(m_mainPanel.getElement()));
		t_configPanel.add(new HTML("<b>配置提示：</b>"));
		t_configPanel.add(m_configPrompt);
				
		final String t_width = "20px";
		m_startHour.setWidth(t_width);
		m_startMinutes.setWidth(t_width);
		m_endHour.setWidth(t_width);
		m_endMinutes.setWidth(t_width);
		
		HorizontalPanel t_timePanel = new HorizontalPanel();
		t_timePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		t_timePanel.add(new HTML("出单时间配置（24小时格式）："));
		t_timePanel.add(m_startHour);
		t_timePanel.add(new HTML(":"));
		t_timePanel.add(m_startMinutes);
		t_timePanel.add(new HTML("—"));
		t_timePanel.add(m_endHour);
		t_timePanel.add(new HTML(":"));
		t_timePanel.add(m_endMinutes);
		
		VerticalPanel vp = new VerticalPanel();
		vp.setWidth("500px");
		vp.setHeight("478px");
		vp.add(m_configToolbar);
		vp.add(m_configPrompt);
		
		m_configPrompt.setWidth("100%");
		m_configPrompt.setHeight("400px");
		m_configToolbar.setWidth("100%");
         
		t_configPanel.add(vp);
		t_configPanel.add(t_timePanel);
		
		Button t_btn = new Button("提交更改");
		t_configPanel.add(t_btn);
		t_btn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				changeConfig();
			}
		});
		
		add(t_configPanel);
		
		// account panel
		//
		Button t_addBtn = new Button("增加账户");
		t_addBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				m_incModifyDlg.show(null);			
			}
		});
		
		Button t_refreshBtn = new Button("刷新");
		t_refreshBtn.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				CommonDialog.PopupWaiting("正在刷新……");
				requestData();
			}
		});
		
		VerticalPanel t_accPanel = new YuchSimplePanel();
		t_accPanel.setSpacing(5);
		t_accPanel.setWidth(CommonDialog.getElementWidth(m_mainPanel.getElement()));
		t_accPanel.add(new HTML("<b>账户列表：</b>"));
				
		HorizontalPanel t_btnsPanel = new HorizontalPanel();
		t_btnsPanel.setSpacing(3);
		t_btnsPanel.add(t_refreshBtn);
		t_btnsPanel.add(t_addBtn);
		
		t_accPanel.add(t_btnsPanel);
		t_accPanel.add(m_accountTable);
		
		add(t_accPanel);
	}
	
	public void requestData(){
				
		try{
			MainPage.fsm_server.getCurrUserList(new AsyncCallback<String>(){
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt("requestData failure：" + caught.getMessage(), ConfigAccPanel.this);
					CommonDialog.HideWaiting();
				}

				public void onSuccess(String result) {
					
					CommonDialog.HideWaiting();
					if(result.startsWith("<Error>")){
						CommonDialog.PopupPrompt(result,ConfigAccPanel.this);
					}else{
						try{
							m_accountList.clear();
							
							YuchJSONObject t_json = new YuchJSONObject(result);
							int num = t_json.m_jsonArray.size();
							
							synchronized (m_accountList) {

								for(int i = 0;i < num;i++){
									User t_user = new User();
									t_user.fromJSON(new YuchJSONObject((JSONObject)t_json.m_jsonArray.get(i)));
									
									m_accountList.add(t_user);
								}
							}
							
							refreshAccountList();
							
						}catch(Exception e){
							CommonDialog.HideWaiting();
							CommonDialog.PopupPrompt("requestData exception",e,ConfigAccPanel.this);
						}
						
					}
					
				}
			});
		}catch(Exception e){
			CommonDialog.PopupPrompt("requestData ",e,ConfigAccPanel.this);
			CommonDialog.HideWaiting();
		}
	}
	
	private class IncModifyUserDlg extends DialogBox{
		
		User m_modifyUser = null;
		
		TextBox	m_name			= new TextBox();
		
		PasswordTextBox	m_pass	= new PasswordTextBox();
		TextBox m_remainMoney	= new TextBox();
		
		
		public IncModifyUserDlg(){
			
			super(false,true);			
			
			VerticalPanel t_mainPanel = new VerticalPanel();
			t_mainPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
			t_mainPanel.setSpacing(10);
			
			int t_line	= 0;
			FlexTable t_table = new FlexTable();
			CommonDialog.AddLabelWidget(t_table, "名字", m_name, t_line++);
			CommonDialog.AddLabelWidget(t_table, "密码", m_pass, t_line++);
			CommonDialog.AddLabelWidget(t_table, "余额", m_remainMoney, t_line++);
			t_mainPanel.add(t_table);
			
			HorizontalPanel t_btnPanel = new HorizontalPanel();
			t_btnPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
			t_btnPanel.setSpacing(5);
			final Button t_config = new Button("确定");
			final Button t_cancel = new Button("取消");
					
			t_btnPanel.add(t_config);
			t_btnPanel.add(t_cancel);
			
			t_mainPanel.add(t_btnPanel);
			setWidget(t_mainPanel);
			
			setGlassEnabled(true);
			setAnimationEnabled(true);			
		
			t_config.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					String t_name		= m_name.getText();
					String t_moneyStr	= m_remainMoney.getText();
					String t_pass		= m_pass.getText();
					
					if(!ShareField.isLeagalName(t_name)){
						CommonDialog.PopupPrompt("需要加入合法的不带符号的名字", IncModifyUserDlg.this);
						return;
					}
					
					if(t_pass.isEmpty()){
						CommonDialog.PopupPrompt("需要填写密码", IncModifyUserDlg.this);
						return;
					}
					
					boolean t_found = false;
					synchronized (m_accountList) {
						for(User u:m_accountList){
							if(u.getName().equalsIgnoreCase(t_name)){
								t_found = true;
								break;
							}
						}
					}
					if(m_modifyUser == null){
						if(t_found){
							CommonDialog.PopupPrompt("已经有这个叫 [" + t_name + "] 的用户了。", IncModifyUserDlg.this);
							return;
						}
					}else{
						if(!t_found){
							CommonDialog.PopupPrompt("找不到 [" + t_name + "] 的用户了。", IncModifyUserDlg.this);
							return;
						}
					}
										
					double t_money = 0;
					try{
						t_money = Double.valueOf(t_moneyStr).doubleValue();
					}catch(Exception e){
						CommonDialog.PopupPrompt("需要输入数字",m_remainMoney);
						return;
					}					
					
					try{
						
						CommonDialog.PopupWaiting("正在提交...");
						
						AsyncCallback<String>t_callback = new AsyncCallback<String>(){
							public void onFailure(Throwable caught){
								CommonDialog.HideWaiting();
								CommonDialog.PopupPrompt("Failure：" + caught.getMessage(), IncModifyUserDlg.this);
							}

							public void onSuccess(String result) {
								CommonDialog.HideWaiting();
								
								if(result.startsWith("<Error>")){
									CommonDialog.PopupPrompt(result,ConfigAccPanel.this);
								}else{
									
									try{
										
										if(m_modifyUser == null){
											
											// add user operation
											//
											User u = new User();
											u.fromJSON(new YuchJSONObject(result));
											m_accountList.add(u);
										}else{
											
											// modify user
											//
											m_modifyUser.fromJSON(new YuchJSONObject(result));
										}
										
										refreshAccountList();
										
									}catch(Exception e){
										CommonDialog.PopupPrompt("exception",e,IncModifyUserDlg.this);
									}
								
									hide();
								}
							}
						};
						
						if(m_modifyUser != null){
							
							User t_user = m_modifyUser.cloneUser();
														
							t_user.setPass(t_pass);
							t_user.setRemainMoney(t_money);
							
							MainPage.fsm_server.modifyUser(t_user.toJSON().toString(),t_callback);
							
						}else{
							
							User t_user = new User();
							t_user.setName(t_name);
							t_user.setPass(t_pass);
							t_user.setRemainMoney(t_money);
							
							MainPage.fsm_server.addUser(t_user.toJSON().toString(),t_callback);
						}
					}catch(Exception e){
						CommonDialog.HideWaiting();
						CommonDialog.PopupPrompt("IncModifyUserDlg",e,IncModifyUserDlg.this);
					}
				}
				
			});
			
			t_cancel.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					hide();
				}
			});
		}
		
		public void show(User _modifyUser){
			
			m_modifyUser = _modifyUser;
			
			if(m_modifyUser != null){
				
				m_name.setText(m_modifyUser.getName());
				m_pass.setText(m_modifyUser.getPass());
				m_remainMoney.setText(Double.toString(m_modifyUser.getRemainMoney()));
				
				m_name.setEnabled(false);
				m_remainMoney.setFocus(true);
				
				setText("修改账户");
				
			}else{
				
				m_name.setText("");
				m_remainMoney.setText("");
				
				m_name.setEnabled(true);
				m_name.setFocus(true);
				
				setText("添加账户");
			}
			
			center();
			show();
		}
	}
	
	IncModifyUserDlg m_incModifyDlg = new IncModifyUserDlg();
	
	private void refreshAccountList(){
		
		m_accountTable.removeAllRows();
		
		int t_column = 0;
		m_accountTable.setHTML(0, t_column++, "<b>名字</b>");
		m_accountTable.setHTML(0, t_column++, "<b>余额</b>");
		m_accountTable.setHTML(0, t_column++, "<b>一共消费</b>");
		m_accountTable.setHTML(0, t_column++, "<b>修改</b>");
		m_accountTable.setHTML(0, t_column++, "<b>删除</b>");
		
		for(int i = 0;i < m_accountList.size();i++){
			final User u = m_accountList.get(i);
			t_column = 0;
			
			final Button t_del 	= new Button("删除");
			final Button t_modify = new Button("修改");
			
			m_accountTable.setHTML(i + 1, t_column++, u.getName());
			m_accountTable.setHTML(i + 1, t_column++, "￥" + u.getRemainMoney());
			m_accountTable.setHTML(i + 1, t_column++, "￥" + u.getTotalPay());
			m_accountTable.setWidget(i + 1, t_column++, t_modify);
			m_accountTable.setWidget(i + 1, t_column++, t_del);
			
			t_del.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					CommonDialog.PopupYesNoDlg("你要删除 ["+u.getName()+"]账户么？", new YesNoHandler() {
						
						@Override
						public void Process() {
							t_del.setEnabled(false);
							
							try{
								MainPage.fsm_server.delUser(u.getName(), new AsyncCallback<String>() {
									public void onFailure(Throwable caught) {
										t_del.setEnabled(true);
										CommonDialog.PopupPrompt("del Failure：" + caught.getMessage(), ConfigAccPanel.this);
									}

									public void onSuccess(String result) {
										t_del.setEnabled(true);
										
										if(result.startsWith("<Error>")){
											CommonDialog.PopupPrompt(result,ConfigAccPanel.this);
										}else{
											try{
												m_accountList.remove(u);
												refreshAccountList();
												
											}catch(Exception e){
												CommonDialog.PopupPrompt("del exception",e,ConfigAccPanel.this);
											}
											
										}
										
									}
								});
							}catch(Exception e){
								t_del.setEnabled(true);
								CommonDialog.PopupPrompt("refreshAccountList del",e,ConfigAccPanel.this);
							}
						}
					},null);					
				}
			});
			
			t_modify.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					m_incModifyDlg.show(u);					
				}
			});
		}
	}
	
	private void changeConfig(){
		
		try{
			
			int t_startHour = Integer.valueOf(m_startHour.getText()).intValue();
			int t_startMinutes = Integer.valueOf(m_startMinutes.getText()).intValue();
			int t_endHour = Integer.valueOf(m_endHour.getText()).intValue();
			int t_endMinutes = Integer.valueOf(m_endMinutes.getText()).intValue();
			
			if(t_startHour < 0 || t_startHour >= 24
			|| t_startMinutes < 0 || t_startMinutes >= 60
			|| t_endHour < 0 || t_endHour >= 24
			|| t_endMinutes < 0 || t_endMinutes >= 60){
				CommonDialog.PopupPrompt("时间格式不正确！", this);
				return ;
			}
			
			if((t_endHour < t_startHour) || (t_endHour == t_startHour && t_endMinutes <= t_startMinutes)){
				CommonDialog.PopupPrompt("结束时间必须大于开始时间。", this);
				return ;
			}
			
			m_storeConfig.setStartTime(t_startHour, t_startMinutes);
			m_storeConfig.setEndTime(t_endHour, t_endMinutes);
			m_storeConfig.setPrompt(m_configPrompt.getHTML());			
			
			MainPage.fsm_server.setConfig(m_storeConfig.toJSON().toString(),new AsyncCallback<String>(){
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt("设置配置信息失败：" + caught.getMessage(), ConfigAccPanel.this);
				}

				public void onSuccess(String result) {
					CommonDialog.PopupPrompt(result,ConfigAccPanel.this);
				}
			});
			
		}catch(Exception e){
			CommonDialog.PopupPrompt("设置配置信息异常：" + e.getMessage(), this);
		}
		
	}
	
	static public void refreshConfig(Config _config){
		if(sm_configPanel != null){
			sm_configPanel.refreshConfigImpl(_config);
		}
	}
	
	private void refreshConfigImpl(Config _config){
		m_configPrompt.setHTML(_config.getPrompt());
		m_startHour.setText(Integer.toString(_config.getStartHour()));
		m_startMinutes.setText(Integer.toString(_config.getStartMinutes()));
		
		m_endHour.setText(Integer.toString(_config.getEndHour()));
		m_endMinutes.setText(Integer.toString(_config.getEndMinutes()));
		
		m_storeConfig = _config;
	}
	
	
}
